<?php

class Light_Service_Manager
{
    /**
     * @var Light_Service_Manager
     */
    protected static $_instance;

    /**
     * @var array of Light_Service_Proxy
     */
    protected $_services = array();

    /**
     * @return Light_Service_Manager
     */
    public static function getInstance()
    {
        if (self::$_instance === null) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /**
     * Singleton
     */
    protected function __construct() {}

    /**
     * Singleton
     */
    protected function __clone() {}

    /**
     * @param string $name
     * @param mixed $service
     * @param mixed $params
     * @throws Light_Exception
     * @return Light_Service_Manager
     */
    public function set($name, $service, array $params = array())
    {
        if (!preg_match('/[a-z][a-z0-9]*?/i', $name)) {
            throw new Light_Exception("Service '{$name}' is not valid");
        }

        if (array_key_exists($name, $this->_services)) {
            throw new Light_Exception("Service '{$name}' is registered already");
        }

        $this->_services[$name] = new Light_Service_Proxy($service, $params);

        return $this;
    }

    /**
     * @param string $name
     * @param boolean $new
     * @throws Light_Exception
     * @return Light_Service_Proxy
     */
    public function get($name, $new = false)
    {
        if (!array_key_exists($name, $this->_services)) {
            throw new Light_Exception("Service '{$name}' is not registered");
        }

        return $this->_services[$name]->execute($new);
    }
}